package com.wlx.common.message.sms;

import com.wlx.common.core.utils.AESUtil;
import com.wlx.common.core.utils.MapUtil;
import com.wlx.common.core.utils.http.HttpUtil;
import com.wlx.common.message.Sender;
import com.wlx.common.message.util.ObjectUtil;
import com.wlx.common.message.util.scheduler.SchedulerUtil;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;


public class YiMeiSmsSender implements Sender {
    @Override
    public boolean send(String phone, String message, String title, Map<String, Object> smsSenderParameter) throws Exception {
        Map<String, Object> parameterMap = new HashMap<>(2);
        parameterMap.put("mobile", phone);
        parameterMap.put("content", title + message);
        String paramJson = ObjectUtil.toJson(parameterMap);
        byte[] data = paramJson.getBytes(Charset.forName("UTF-8"));
        byte[] outData = AESUtil.getInstance().encrypt(data, smsSenderParameter.get("secretKey").toString().getBytes());
        HttpUtil.HttpResponse response = null;
        try {
            response = HttpUtil.connection(smsSenderParameter.get("smsApi").toString())
                    .setHeader("appId", smsSenderParameter.get("appId").toString()).setPostParameter(outData).post();
        } catch (IOException e) {
            throw e;
        }
        byte[] inData = AESUtil.getInstance().decrypt(response.getResponse(), smsSenderParameter.get("secretKey").toString().getBytes());
        return true;
    }

    @Override
    public boolean syncSend(String phone, String message, String title, Map<String, Object> smsSenderParameter) throws Exception {
        SchedulerUtil.schedule(() -> {
            send(phone, message, title, smsSenderParameter);
        });
        return true;
    }

    @Override
    public Map<String, Object> senderParameterTemplate() {
        return MapUtil.builder().elem("appId", "由亿美后台获取，类似：KUCD-EBY-EMS1-1YGGG")
                .elem("secretKey", "由亿美后台获取，类似：EC6563202771328D")
                .elem("host", "由亿美提供，类似：http://bjmtn.b2m.cn")
                .elem("smsApi", "由亿美提供，类似：http://bjmtn.b2m.cn/inter/sendSingleSMS").build();
    }
}
